package nbcp

import nbcp.base.comm.SystemContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextRefreshedEvent

import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
import nbcp.base.extend.JavascriptDateModule
import nbcp.base.extend.MyJsonMapper
import nbcp.base.utf8
import nbcp.db.redis.rer
import nbcp.web.RequestParameterConverter
import java.io.ByteArrayInputStream
import java.io.ObjectInputStream
import java.io.Serializable


@Configuration
open class PzxWebOrmInit : ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    lateinit var handerAdapter: RequestMappingHandlerAdapter


    @Autowired
    lateinit var converter: MappingJackson2HttpMessageConverter

    @Autowired
    private lateinit var jsonModule: JavascriptDateModule

    override fun onApplicationEvent(event: ContextRefreshedEvent) {
        initSystemContext();

        initMvcRequest()

        initMvcResponse()
    }


    private fun initMvcRequest() {
//        genericConversionService.addConverter(Date2LocalDateTimeConverter())

        var listResolvers = mutableListOf<HandlerMethodArgumentResolver>()
        listResolvers.add(RequestParameterConverter());

        listResolvers.addAll(handerAdapter.argumentResolvers ?: listOf())

        handerAdapter.argumentResolvers = listResolvers;
    }


    private fun initMvcResponse() {
        //注册返回的消息体。
        handerAdapter.messageConverters.filter { it is MappingJackson2HttpMessageConverter }.map { it as MappingJackson2HttpMessageConverter }.forEach {
            it.objectMapper = MyJsonMapper.instance
        }

        //设置 StringHttpMessageConverter 的字符集
        handerAdapter.messageConverters.filter { it is StringHttpMessageConverter }.map { it as StringHttpMessageConverter }.forEach {
            it.setWriteAcceptCharset(false)
            it.defaultCharset = utf8
        }
    }


    private fun initSystemContext() {
        SystemContext.getSessionData = { token, field ->
            var data = rer.sys.sessionData.get(token, field)
            if (data == null) {
                null
            } else {
                ObjectInputStream(ByteArrayInputStream(data)).readObject() as Serializable?
            }
        }

    }
}

